<script setup lang="ts" name="UserForm">
import { ref, reactive, watch, defineProps, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import type { User, UserCreateRequest, UserUpdateRequest } from '@/model/user-role-model'
import { UserStatus } from '@/model/user-role-model'
import { getRoles } from '@/request/user-role-api'
import { createUser, updateUser } from '@/request/user-role-api'
import type { Role } from '@/model/user-role-model'

const props = defineProps<{
  visible: boolean
  title: string
  user?: User | null
}>()

const emit = defineEmits<{
  (e: 'update:visible', visible: boolean): void
  (e: 'saved'): void
}>()

// 表单引用
const formRef = ref<FormInstance>()

// 角色列表
const roleOptions = ref<Role[]>([])
const loadingRoles = ref(false)

// 表单数据
const formData = reactive<UserCreateRequest & UserUpdateRequest>({
  login_name: '',
  full_name: '',
  password: '',
  confirm_password: '',
  role_id: 0,
  status: UserStatus.ACTIVE,
  department: '',
  id: 0
})

// 表单校验规则
const rules = reactive<FormRules>({
  login_name: [
    { required: true, message: '请输入登录名', trigger: 'blur' },
    { min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' }
  ],
  full_name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  password: [
    { required: !props.user, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码不能少于 6 个字符', trigger: 'blur' }
  ],
  confirm_password: [
    { required: !props.user, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (!props.user && value !== formData.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  role_id: [
    { required: true, message: '请选择角色', trigger: 'change' },
    { type: 'number', min: 1, message: '请选择角色', trigger: 'change' }
  ]
})

// 获取角色列表
const fetchRoles = async () => {
  loadingRoles.value = true
  try {
    const res = await getRoles()
    if (res.code === 0 && res.data) {
      // 判断返回的data是数组还是包含roles和total的对象
      if (Array.isArray(res.data)) {
        roleOptions.value = res.data
      } else if (res.data && 'roles' in res.data) {
        roleOptions.value = res.data.roles
      }
    } else {
      ElMessage.error(res.errorMsg || '获取角色列表失败')
    }
  } catch (error) {
    console.error('获取角色列表出错：', error)
    ElMessage.error('获取角色列表失败')
  } finally {
    loadingRoles.value = false
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let res
        
        if (props.user) {
          // 更新用户
          const updateData: UserUpdateRequest = {
            id: props.user.id,
            full_name: formData.full_name,
            role_id: formData.role_id,
            status: formData.status,
            department: formData.department
          }
          res = await updateUser(props.user.id, updateData)
        } else {
          // 创建用户
          const createData: UserCreateRequest = {
            login_name: formData.login_name,
            full_name: formData.full_name,
            password: formData.password,
            confirm_password: formData.confirm_password,
            role_id: formData.role_id,
            status: formData.status,
            department: formData.department
          }
          res = await createUser(createData)
        }
        
        if (res.code === 0) {
          ElMessage.success(props.user ? '更新成功' : '创建成功')
          closeDialog()
          emit('saved')
        } else {
          ElMessage.error(res.errorMsg || (props.user ? '更新失败' : '创建失败'))
        }
      } catch (error) {
        console.error(props.user ? '更新用户出错：' : '创建用户出错：', error)
        ElMessage.error(props.user ? '更新失败' : '创建失败')
      }
    }
  })
}

// 关闭弹窗
const closeDialog = () => {
  emit('update:visible', false)
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 监听用户数据变化
watch(
  () => props.user,
  (newVal) => {
    if (newVal) {
      formData.id = newVal.id
      formData.login_name = newVal.login_name
      formData.full_name = newVal.full_name
      formData.role_id = newVal.role_id
      formData.status = newVal.status
      formData.department = newVal.department || ''
      
      // 编辑用户时不需要输入密码
      formData.password = ''
      formData.confirm_password = ''
    } else {
      resetForm()
    }
  },
  { immediate: true }
)

// 监听弹窗显示状态
watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      fetchRoles()
    }
  },
  { immediate: true }
)
</script>

<template>
  <el-dialog
    :title="title"
    :model-value="visible"
    @update:model-value="(val) => emit('update:visible', val)"
    :close-on-click-modal="false"
    width="500px"
    @closed="closeDialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
      label-position="right"
    >
      <el-form-item label="登录名" prop="login_name">
        <el-input 
          v-model="formData.login_name" 
          placeholder="请输入登录名"
          :disabled="!!user"
        />
      </el-form-item>
      
      <el-form-item label="姓名" prop="full_name">
        <el-input v-model="formData.full_name" placeholder="请输入姓名" />
      </el-form-item>
      
      <template v-if="!user">
        <el-form-item label="密码" prop="password">
          <el-input 
            v-model="formData.password" 
            type="password" 
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirm_password">
          <el-input 
            v-model="formData.confirm_password" 
            type="password" 
            placeholder="请再次输入密码"
            show-password
          />
        </el-form-item>
      </template>
      
      <el-form-item label="角色" prop="role_id">
        <el-select 
          v-model="formData.role_id" 
          placeholder="请选择角色" 
          class="w-full"
          :loading="loadingRoles"
        >
          <el-option 
            v-for="role in roleOptions" 
            :key="role.id" 
            :label="role.name" 
            :value="role.id" 
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="部门" prop="department">
        <el-input v-model="formData.department" placeholder="请输入所属部门" />
      </el-form-item>
      
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio :label="UserStatus.ACTIVE">激活</el-radio>
          <el-radio :label="UserStatus.DISABLED">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>
